// import 'webrtc-adapter'
import axios from "axios";

const _axios = axios.create();

// window.id_pc_map = {}

export async function connectStream(url) {
  return new Promise((resolve, reject) => {
    // const { CONFIG = {}, axios } = window || {}
    // const { zlkServer, zlkPath } = CONFIG
    const catchFn = function (e) {
      reject(e);
    };
    const pc = new RTCPeerConnection(null);
    let resolved = false;
    pc.ontrack = (event) => {
      if (resolved) return;
      resolved = true;
      const [stream] = event.streams;
      resolve({ pc, stream });
    };
    const transceiverInit = {
      direction: "recvonly",
      sendEncodings: []
    };
    pc.addTransceiver("audio", transceiverInit);
    pc.addTransceiver("video", transceiverInit);
    pc.createOffer()
      .then((desc) => {
        pc.setLocalDescription(desc)
          .then(() => {
            _axios({
              url,
              headers: {
                "Content-Type": "text/plain;charset=utf-8"
              },
              method: "post",
              data: desc.sdp,
              responseType: "json"
            })
              .then((ret) => {
                const { code, sdp } = ret.data;
                if (code !== 0) {
                  reject(new Error(`zlk axios response code: ${code}`));
                }
                pc.setRemoteDescription({ type: "answer", sdp }).catch(catchFn);
              })
              .catch(catchFn);
          })
          .catch(catchFn);
      })
      .catch(catchFn);
  });
}
